package com.xmb.quick.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class MyClassLoader extends ClassLoader{

	private String codeBytePath;
	
	public MyClassLoader(String codeBytePath) {
		super();
		this.codeBytePath = codeBytePath;
	}

	@Override
	protected Class<?> findClass(String className) throws ClassNotFoundException {
		BufferedInputStream bis = null;
		ByteArrayOutputStream bos = null;
		try {
			String fileName = codeBytePath + className + ".class";
			bis = new BufferedInputStream(new FileInputStream(fileName));
			bos = new ByteArrayOutputStream();
			
			int len;
			byte[] data = new byte[1024];
			while((len = bis.read()) != -1) {
				bos.write(data, 0, len);
			}
			byte[] byteArray = bos.toByteArray();
			Class<?> defineClass = defineClass(null,byteArray, 0, byteArray.length);
			return defineClass;
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(bis != null)
					bis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if(bos != null)
					bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
}
